import psycopg2, traceback
from datetime import datetime


class JobsDb:

    def __init__(self, maxErrorToRest = 3):
        self.__conn = psycopg2.connect("dbname=postgres user=postgres")
        self.__errorCount = 0
        self.__maxError = maxErrorToRest

    def InsertJob(self, batchPath, startInd,endInd):
        if (self.__conn == None):
            raise NameError('Connection already closed')
        try:
            self.__cur = self.__conn.cursor()
            self.__cur.execute("""insert into jobs.work_batch(insertion_time, batch_path,start_index,end_index) select now(), %s, %s, %s
                                WHERE NOT EXISTS (SELECT id FROM jobs.work_batch WHERE batch_path=%s and start_index=%s);""",
                               (batchPath, startInd, endInd, batchPath, startInd))
            self.__cur.close()
            self.__conn.commit()
        except:
            traceback.print_exc()
            self.__errorCount = self.__errorCount + 1
            if (self.__errorCount >= self.__maxError):
                self.__errorCount = 0
                try:
                    self.__conn.close()
                except:
                    traceback.print_exc()
                self.__conn = psycopg2.connect("dbname=postgres user=postgres")
       

    def Close(self):
        self.__conn.close()
        self.__conn =  None

    


